﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using Code.Commen;
using Code.DAL;
using System.Data.SqlClient;

namespace Code.BLL
{
    public class PlayTypeOptionManage : ManageBase<PlayTypeOption>
    {


        public int Update(NameValue<long, NameValue<string, object>> update)
        {
            int rs = base.Update(update.ToNameValue(p => (object)new { ID = p.Key }, p => (object)p.Value));
            if (rs > 0)
            {
                var winid = base.Select(s => s.Where(p => update.Select(pp => pp.Key).Contains(p.ID))
                    .Select(p => (object)new { p.PlayTypeID, p.WinMoneyModelID }).ToArray());
                base.Delete<PlayTypeOption_User>(winid);
            }
            return rs;
        }

        /// <summary>
        /// 获取奖金设置 注（返点为小数，需要乘以100）
        /// </summary>
        /// <param name="uid">用户的ID ，为空则获取站点的设置</param>
        /// <param name="ckUseSite">是否检查使用站点设置</param>
        /// <returns></returns>
        public WinMoneyOption[] GetWinMoneyOption(Guid? uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            int? type = lottery.HasValue ? ((int)((LotteryType)lottery.Value).GetDefaultLottery()) as int? : null;
            WinMoneyOption[] rs;
            var playuser = base.Select<PlayTypeOption_User, IQueryable<PlayTypeOption_User>>(s => s);
            var playsite = base.Select(s => s);
            var useSiteWin = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            var useSiteBack = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);

            if (winModel.HasValue)
            {
                playsite = playsite.Where(p => p.WinMoneyModelID == winModel.Value);
                playuser = playuser.Where(p => p.WinMoneyModelID == winModel.Value);
            }
            if (lottery.HasValue)
            {
                playsite = playsite.Where(p => p.PlayType.LotteryID == type);
                playuser = playuser.Where(p => p.PlayType.LotteryID == type);
            }
            if (!uid.HasValue)
            {
                rs = playsite.Select(p => new WinMoneyOption
                {
                    LotteryID = p.PlayType.LotteryID,
                    PlayTypeListID = p.PlayType.PlayTypeListID,
                    BackMoneyTypeID = p.PlayType.BackMoneyTypeID,

                    PlayTypeID = p.PlayTypeID,
                    WinMoneyModelID = p.WinMoneyModelID,
                    WinMoney = (double)p.WinMoney,
                    BackMoneyRatio = (double)p.BackMoneyRatio,

                    BackMoneyToWinMoneyRatio = (double)p.BackMoneyToWinMoneyRatio,
                    MaxBackMoneyToWinMoney = (double)p.MaxBackMoneyToWinMoney,
                }).ToArray();
            }
            else
            {
                var user = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.ID == uid));
                if (user == null)
                    throw new ValidateException("用户不存在");
                var commanders = user.Commands.Split("&".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => new Guid(p));
                playuser = playuser.Where(p => p.UserID == uid.Value || commanders.Contains(p.UserID));

                rs = playsite
                   .GroupJoin(playuser, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (site, users) => new { site, users = users })
                   .SelectMany(p => p.users.DefaultIfEmpty(), (p1, p2) => new { p1.site, user = p2, })
                   .GroupBy(p => new { p.site.PlayTypeID, p.site.WinMoneyModelID }, p => new WinMoneyOption
                   {
                        LotteryID = p.site.PlayType.LotteryID,
                        PlayTypeListID = p.site.PlayType.PlayTypeListID,
                        BackMoneyTypeID = p.site.PlayType.BackMoneyTypeID,
                        PlayTypeID = p.site.PlayTypeID,
                        WinMoneyModelID = p.site.WinMoneyModelID,
                        UserID = uid,
                        WinMoney = (double)(ckUseSite && useSiteWin ? p.site.WinMoney : p.user.WinMoney as decimal? ?? p.site.WinMoney),
                        BackMoneyRatio = (double)(ckUseSite && useSiteBack ? p.site.BackMoneyRatio : p.user.BackMoneyRatio as decimal? ?? p.site.BackMoneyRatio),

                        BackMoneyToWinMoneyRatio = (double)p.site.BackMoneyToWinMoneyRatio,
                        MaxBackMoneyToWinMoney = (double)p.site.MaxBackMoneyToWinMoney,
                    }).Select(p =>
                        p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                    ).ToArray();
            }
            if (replace && type.HasValue && type != lottery)
            {
                rs.Each(p =>
                {
                    var tp = CacheManage.PlayType.Values.FirstOrDefault(pp => pp.PlayTypeListID == p.PlayTypeListID && pp.LotteryID == lottery);
                    if (tp != null)
                        p.PlayTypeID = tp.ID;
                });
            }
            return rs;
        }
        /// <summary>
        /// 根据元角模式 获取奖金设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">用户ID，为空时取站点设置</param>
        public WinMoneyOption[] GetUserOptionByRatio(Guid? uid, int? lottery, int? winModel, decimal ratioModel)
        {
            var _ratio = CacheManage.Ratio[ratioModel];
            var data = GetWinMoneyOption(uid, lottery, winModel, true, true).ToArray();

            data.Each(p=>
                {
                    p.WinMoney = Math.Round(p.WinMoney * (double) _ratio.Ratio, 9);
                    p.BackMoneyRatio = Math.Round((p.BackMoneyRatio - (double) _ratio.BackMoneyDifference) * 100, 9);
                    p.MaxBackMoneyToWinMoney = Math.Round(p.MaxBackMoneyToWinMoney * 100, 9);
                    p.BackMoneyToWinMoneyRatio = Math.Round(p.BackMoneyToWinMoneyRatio * (double) _ratio.Ratio, 9);
                });

            return data;
        }
        /// <summary>
        /// 获取用户和上级的奖金/返点  注（返点为小数，需要乘以100）
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="lottery"></param>
        /// <param name="winModel"></param>
        /// <param name="ckUseSite"></param>
        /// <param name="replace"></param>
        /// <returns></returns>
        public IDictionary<Guid, IEnumerable<WinMoneyOption>> GetSelfAndCommanderOptions(Guid uid, int lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            var user = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.ID == uid));
            if (user == null)
                throw new ValidateException("用户不存在");
            var commanders = user.Commands.Split("&".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => new Guid(p));

            var rs = new Dictionary<Guid, IEnumerable<WinMoneyOption>>();
            foreach (var item in commanders)
            {
                var option = GetWinMoneyOption(item, lottery, winModel, ckUseSite, replace);
                rs.Add(item, option);
            }
            rs.Add(uid, GetWinMoneyOption(uid, lottery, winModel, ckUseSite, replace));

            return rs;
        }
        /// <summary>
        ///前台 跟据用户与上级的奖金/返点 减去差值 设置该用户的奖金/返点
        /// 用户的下级也将有所影响
        /// </summary>
        /// <param name="uid">要设置的用户</param>
        /// <param name="winMoneyRatio">要调整的奖金差比率</param>
        /// <param name="backMoneyMargin">要调整的返点差</param>
        /// <param name="lottery">彩种</param>
        public int SetOptionByMargin(Guid? command, Guid uid, int? winmodel, LotteryType? lottery, double? winMoneyRatio, double? backMoneyMargin, bool isNewUser, bool manage)
        {
            if (winMoneyRatio.HasValue && (winMoneyRatio > 100 || winMoneyRatio < 0))
                return -1;
            if (backMoneyMargin.HasValue && (backMoneyMargin > 100 || backMoneyMargin < 0))
                return -1;
            int rs = 1;
            if (!winMoneyRatio.HasValue && !backMoneyMargin.HasValue)
                return rs;

            var cmds = GetUserOption_SetWithChild(command, (int?)lottery, winmodel, false, false);
            var self = cmds.ToDictionary(p => new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }, p => new { p.Option.BackMoneyRatio, p.Option.WinMoney });

            var memberMax = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            if (cmds.Count() > 0)
            {
                var curr = base.Select<PlayTypeOption_User, IEnumerable<PlayTypeOption_User>>(s => s.Where(p => p.UserID == uid)).ToArray();
                var ins = new List<object>();
                var ups = new NameValue<object, object>();
                int state = 1;
                foreach (var p in cmds)
                {
                    if (winMoneyRatio.HasValue)
                        p.Option.WinMoney = p.Option.WinMoney - p.Option.WinMoney * winMoneyRatio.Value / 100;
                    if (backMoneyMargin.HasValue)
                        p.Option.BackMoneyRatio = p.Option.BackMoneyRatio - backMoneyMargin.Value;

                    p.Option.WinMoney = Math.Min(p.Option.WinMoney, p.MaxWinMoney);
                    p.Option.WinMoney = Math.Max(p.Option.WinMoney, p.MinWinMoney);
                    if (!manage)
                        p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, memberMax);
                    //p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, p.MaxBackMoneyRatio);
                    //p.Option.BackMoneyRatio = Math.Max(p.Option.BackMoneyRatio, p.MinBackMoneyRatio);

                    p.Option.BackMoneyRatio /= 100;
                    if (curr.Any(p1 => p1.PlayTypeID == p.Option.PlayTypeID && p1.WinMoneyModelID == p.Option.WinMoneyModelID))
                        ups.Add(new { WinMoney = new SqlExpression(winMoneyRatio.HasValue ? "{0}" : "[WinMoney]", p.Option.WinMoney), BackMoneyRatio = new SqlExpression(backMoneyMargin.HasValue ? "{0}" : "[BackMoneyRatio]", p.Option.BackMoneyRatio) },
                            new { p.Option.PlayTypeID, p.Option.WinMoneyModelID, UserID = uid });
                    else

                        ins.Add(new { UserID = uid, p.Option.PlayTypeID, p.Option.WinMoneyModelID, p.Option.WinMoney, p.Option.BackMoneyRatio, state });

                    if (!isNewUser)
                    {
                        if (backMoneyMargin.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].BackMoneyRatio != p.Option.BackMoneyRatio)
                            ups.Add(new { BackMoneyRatio = p.Option.BackMoneyRatio }, new
                            {
                                PlayTypeID = p.Option.PlayTypeID,
                                WinMoneyModelID = p.Option.WinMoneyModelID,
                                BackMoneyRatio = new ComparValue(Comparison.GreaterThan, p.Option.BackMoneyRatio),
                                @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.Commands LIKE {0})", string.Format("%{0}%", uid)))
                            });
                        if (winMoneyRatio.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].WinMoney != p.Option.WinMoney)
                            ups.Add(new { WinMoney = p.Option.WinMoney }, new
                            {
                                PlayTypeID = p.Option.PlayTypeID,
                                WinMoneyModelID = p.Option.WinMoneyModelID,
                                WinMoney = new ComparValue(Comparison.GreaterThan, p.Option.WinMoney),
                                @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.Commands LIKE {0})", string.Format("%{0}%", uid)))
                            });
                    }
                }
                base.BeginTransaction();
                base.Insert<PlayTypeOption_User>(ins.ToArray());
                base.Update<PlayTypeOption_User>(ups);
                rs = base.ExecuteTransaction();
            }
            return rs;
        }



        /// <summary>
        ///后台 跟据用户与上级的奖金/返点 减去差值 设置该用户的奖金/返点
        /// 用户的下级也将有所影响
        /// </summary>
        /// <param name="uid">要设置的用户</param>
        /// <param name="winMoneyRatio">要调整的奖金差比率</param>
        /// <param name="backMoneyMargin">要调整的返点差</param>
        /// <param name="lottery">彩种</param>
        public int SetUserOptionByMargin(Guid? command, Guid uid, int? winmodel, LotteryType? lottery, double? winMoneyRatio, double? backMoneyMargin, bool isNewUser, bool manage)
        {
            if (winMoneyRatio.HasValue && (winMoneyRatio > 100 || winMoneyRatio < 0))
                return -1;
            if (backMoneyMargin.HasValue && (backMoneyMargin > 100 || backMoneyMargin < 0))
                return -1;
            int rs = 0;
            var cmds = GetUserOption_SetWithChild(command, (int?)lottery, winmodel, false, false);
            var self = cmds.ToDictionary(p => new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }, p => new { p.Option.BackMoneyRatio, p.Option.WinMoney });

            var memberMax = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            if (cmds.Count() > 0)
            {
                var curr = base.Select<PlayTypeOption_User, IEnumerable<PlayTypeOption_User>>(s=>s);
                var ins = new List<object>();
                var ups = new NameValue<object, object>();
                int state = 0;
                foreach (var p in cmds)
                {
                    if (winMoneyRatio.HasValue)
                        p.Option.WinMoney = p.Option.WinMoney - p.Option.WinMoney * winMoneyRatio.Value / 100;
                    if (backMoneyMargin.HasValue)
                        p.Option.BackMoneyRatio = p.Option.BackMoneyRatio - backMoneyMargin.Value;

                    p.Option.WinMoney = Math.Min(p.Option.WinMoney, p.MaxWinMoney);
                    p.Option.WinMoney = Math.Max(p.Option.WinMoney, p.MinWinMoney);
                    if (!manage)
                        p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, memberMax);
                    p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, p.MaxBackMoneyRatio);
                    p.Option.BackMoneyRatio = Math.Max(p.Option.BackMoneyRatio, p.MinBackMoneyRatio);

                    p.Option.BackMoneyRatio /= 100;
                    if (curr.Any(p1 => p1.PlayTypeID == p.Option.PlayTypeID && p1.WinMoneyModelID == p.Option.WinMoneyModelID))
                        ups.Add(new { WinMoney = new SqlExpression(winMoneyRatio.HasValue ? "{0}" : "[WinMoney]", p.Option.WinMoney), BackMoneyRatio = new SqlExpression(backMoneyMargin.HasValue ? "{0}" : "[BackMoneyRatio]", p.Option.BackMoneyRatio) },
                            new { p.Option.PlayTypeID, p.Option.WinMoneyModelID, UserID = uid });
                    else

                        ins.Add(new { UserID = uid, p.Option.PlayTypeID, p.Option.WinMoneyModelID, p.Option.WinMoney, p.Option.BackMoneyRatio, state });

                    if (!isNewUser)
                    {
                        if (backMoneyMargin.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].BackMoneyRatio != p.Option.BackMoneyRatio)
                            ups.Add(new { BackMoneyRatio = p.Option.BackMoneyRatio }, new
                            {
                                PlayTypeID = p.Option.PlayTypeID,
                                WinMoneyModelID = p.Option.WinMoneyModelID,
                                BackMoneyRatio = new ComparValue(Comparison.GreaterThan, p.Option.BackMoneyRatio),
                                @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.Commands LIKE {0})", string.Format("%{0}%", uid)))
                            });
                        if (winMoneyRatio.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].WinMoney != p.Option.WinMoney)
                            ups.Add(new { WinMoney = p.Option.WinMoney }, new
                            {
                                PlayTypeID = p.Option.PlayTypeID,
                                WinMoneyModelID = p.Option.WinMoneyModelID,
                                WinMoney = new ComparValue(Comparison.GreaterThan, p.Option.WinMoney),
                                @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.Commands LIKE {0})", string.Format("%{0}%", uid)))
                            });
                    }
                }
                base.BeginTransaction();
                base.Insert<PlayTypeOption_User>(ins.ToArray());
                base.Update<PlayTypeOption_User>(ups);
                rs = base.ExecuteTransaction();
            }
            return rs;
        }
        /// <summary>
        /// 后台获取用户返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">要设置的用户ID</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> GetOptionUser_Set(Guid uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;

            var user = base.Select<Users, Users>(s => s.First(p => p.ID == uid));
            if (user == null)
                throw new AppException("用户不存在！");
            var self = this.GetOption(uid, lottery, winModel, ckUseSite, replace);
            var cmd = this.GetOption(null, lottery, winModel, ckUseSite, replace);
            var site = this.GetOption(null, lottery, winModel, ckUseSite, replace);
            items = BuildUserSets(self, cmd, site);
            return items;
        }


        /// <summary>
        ///后台生成奖金设置的内容
        /// </summary>
        /// <param name="self">要设置的用户，为空时表示生成站点的奖金设置 </param>
        /// <param name="cmd">上级的设置</param>
        /// <param name="site">站点的设置</param>
        /// <returns></returns>
        private static IEnumerable<WinMoneyOptionSetItem> BuildUserSets(WinMoneyOption[] self, WinMoneyOption[] cmd, WinMoneyOption[] site)
        {

            IEnumerable<WinMoneyOptionSetItem> items;

            if (self == null && cmd == null)
            {
                items = site.Select(p =>
                {
                    var tp = new WinMoneyOptionSetItem
                    {
                        PlayName = CacheManage.Playlist[(PlayType_E)p.PlayTypeListID].Name,
                        PlayNames = CacheManage.BackMoneyType[Convert.ToInt32(p.BackMoneyTypeID)].Name,
                        LotteryName = CacheManage.Lottery[(LotteryType)p.LotteryID].Name,
                        WinMoneyName = CacheManage.WinModel[p.WinMoneyModelID].Name,
                        BackMoneyName = CacheManage.BackMoneyType[Convert.ToInt32(p.BackMoneyTypeID)].Name,
                        PlaySort = CacheManage.PlayType[p.PlayTypeID].Sort,

                        Option = p,
                    };
                    tp.MaxBackMoneyRatio *= 100;
                    tp.MinBackMoneyRatio *= 100;
                    tp.Option.BackMoneyRatio *= 100;

                    tp.Option.BackMoneyToWinMoneyRatio *= 100;
                    return tp;
                });
            }
            else
            {
                if (self == null)
                    self = cmd;

                // 最低保障金额比率,默认:0
                var MinWinMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinWinMoneyRatio].ToDouble(0) / 100;
                //最大反奖差比率,默认:1
                var MaxBackWinMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MaxBackWinMoneyMarginRatio].ToDouble(100) / 100;
                //最小返奖差比率，默认：0
                var MinBackWinMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackWinMoneyMarginRatio].ToDouble(0) / 100;
                // 最低保障返点比率,默认:0
                var MinBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackMoneyRatio].ToDouble(0) / 100;
                // 最大返点差,默认:1
                var MaxBackMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio].ToDouble(100) / 100;
                // 最小返点差,默认:0
                var MinBackMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio].ToDouble(0) / 100;

                items = self.Join(cmd, p => new { p.BackMoneyTypeID, p.WinMoneyModelID }, p => new { p.BackMoneyTypeID, p.WinMoneyModelID }, (Self, Cmd) => new { Self, Cmd })
                     .Select(p =>
                     {
                         var tp = new WinMoneyOptionSetItem();
                         tp.PlayName = CacheManage.Playlist[(PlayType_E)p.Self.PlayTypeListID].Name;
                         tp.PlayNames = CacheManage.BackMoneyType[Convert.ToInt32(p.Self.BackMoneyTypeID)].Name;
                         tp.LotteryName = CacheManage.Lottery[(LotteryType)p.Self.LotteryID].Name;
                         tp.WinMoneyName = CacheManage.WinModel[p.Self.WinMoneyModelID].Name;
                         tp.BackMoneyName = CacheManage.BackMoneyType[Convert.ToInt32(p.Self.BackMoneyTypeID)].Name;
                         tp.PlaySort = CacheManage.PlayType[p.Self.PlayTypeID].Sort;
                         tp.States = p.Self.States == 0 ? true : false;
                         tp.Option = p.Self;
                         tp.CurrentBackMoneyRatio = p.Cmd.BackMoneyRatio;
                         tp.CurrentWimMoney = p.Cmd.WinMoney;
                         tp.MaxBackMoneyRatio = Math.Max(p.Cmd.BackMoneyRatio - MinBackMoneyMarginRatio, 0);
                         tp.MaxWinMoney = Math.Max(p.Cmd.WinMoney - (p.Cmd.WinMoney * MinBackWinMoneyMarginRatio), 0);
                         tp.MinBackMoneyRatio = Math.Max(Math.Max(MinBackMoneyRatio, p.Cmd.BackMoneyRatio - MaxBackMoneyMarginRatio), 0);


                         if (tp.MinWinMoney > tp.MaxWinMoney)
                             tp.MaxWinMoney = tp.MinWinMoney;
                         if (tp.MinBackMoneyRatio > tp.MaxBackMoneyRatio)
                             tp.MaxBackMoneyRatio = tp.MinBackMoneyRatio;
                         tp.MaxWinMoney = Math.Min(tp.MaxWinMoney, p.Cmd.WinMoney);
                         tp.MinWinMoney = Math.Min(tp.MinWinMoney, p.Cmd.WinMoney);
                         tp.MaxBackMoneyRatio = Math.Min(tp.MaxBackMoneyRatio, p.Cmd.BackMoneyRatio);
                         tp.MinBackMoneyRatio = Math.Min(tp.MinBackMoneyRatio, p.Cmd.BackMoneyRatio);
                         tp.MaxBackMoneyRatio = Math.Round(tp.MaxBackMoneyRatio * 100, 9);
                         tp.MinBackMoneyRatio = Math.Round(tp.MinBackMoneyRatio * 100, 9);
                         tp.Option.BackMoneyRatio = Math.Round(tp.Option.BackMoneyRatio * 100, 9);
                         tp.CurrentBackMoneyRatio = Math.Round(tp.CurrentBackMoneyRatio * 100, 9);

                         tp.Option.BackMoneyToWinMoneyRatio = Math.Round(tp.Option.BackMoneyToWinMoneyRatio * 100, 9);
                         return tp;
                     });
                int cout = 0;
                var resl = items.ToArray();
                List<BackMoneyRatioModel> list = new SiteManage().GetBackMoneyRatios();
                foreach (var item in resl)
                {
                    foreach (var back in list)
                    {
                        if (item.Option.WinMoneyModelID == back.WinModelID)
                        {
                            if (back.key == Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio)
                            {

                                if (resl[cout].Option.MinBackMoneyRatio <= (item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value)))
                                {
                                    resl[cout].Option.MinBackMoneyRatio = item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value);
                                }
                            }
                            else if (back.key == Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio)
                            {
                                if (resl[cout].Option.MaxBackMoneyRatio >= (item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value)))
                                {
                                    resl[cout].Option.MaxBackMoneyRatio = item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value);
                                }

                            }
                        }
                    }
                    cout++;
                }
                items = resl;
            }
            return items;
        }

        public int SetUserSubWinMoneyMargin(Guid uid, int? winmodel, LotteryType? lottery, double? winMoneyRatio, double? backMoneyMargin, bool manage)
        {
            if (winMoneyRatio.HasValue && (winMoneyRatio > 100 || winMoneyRatio < 0))
                return -1;
            if (backMoneyMargin.HasValue && (backMoneyMargin > 100 || backMoneyMargin < 0))
                return -1;

            int rs = 0;

            if (!winMoneyRatio.HasValue && !backMoneyMargin.HasValue)
                return rs;

            var cmds = GetUserOption_SetWithChild(uid, (int?)lottery, winmodel, false, false);
            var self = cmds.ToDictionary(p => new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }, p => new { p.Option.BackMoneyRatio, p.Option.WinMoney });
            var memberMax = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            if (cmds.Count() > 0)
            {
                var ins = new List<object>();
                var ups = new NameValue<object, object>();
                foreach (var p in cmds)
                {
                    if (winMoneyRatio.HasValue)
                        p.Option.WinMoney = p.Option.WinMoney - p.Option.WinMoney * winMoneyRatio.Value / 100;
                    if (backMoneyMargin.HasValue)
                        p.Option.BackMoneyRatio = p.Option.BackMoneyRatio - backMoneyMargin.Value;

                    p.Option.WinMoney = Math.Min(p.Option.WinMoney, p.MaxWinMoney);
                    p.Option.WinMoney = Math.Max(p.Option.WinMoney, p.MinWinMoney);
                    if (!manage)
                        p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, memberMax);
                    p.Option.BackMoneyRatio = Math.Min(p.Option.BackMoneyRatio, p.MaxBackMoneyRatio);
                    p.Option.BackMoneyRatio = Math.Max(p.Option.BackMoneyRatio, p.MinBackMoneyRatio);

                    p.Option.BackMoneyRatio = Math.Round(p.Option.BackMoneyRatio / 100, 9);

                    ups.Add(new { WinMoney = new SqlExpression(winMoneyRatio.HasValue ? "{0}" : "[WinMoney]", p.Option.WinMoney), BackMoneyRatio = new SqlExpression(backMoneyMargin.HasValue ? "{0}" : "[BackMoneyRatio]", p.Option.BackMoneyRatio) }, new
                    {
                        p.Option.PlayTypeID,
                        p.Option.WinMoneyModelID,
                        @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.CommandID = {0})", uid))
                    });

                    if (backMoneyMargin.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].BackMoneyRatio != p.Option.BackMoneyRatio)
                        ups.Add(new { BackMoneyRatio = p.Option.BackMoneyRatio }, new
                        {
                            PlayTypeID = p.Option.PlayTypeID,
                            WinMoneyModelID = p.Option.WinMoneyModelID,
                            BackMoneyRatio = new ComparValue(Comparison.GreaterThan, p.Option.BackMoneyRatio),
                            @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.CommandID <> {1} AND t1.Commands LIKE {0})", string.Format("%{0}%", uid), uid))
                        });

                    if (winMoneyRatio.HasValue && self[new { p.Option.PlayTypeID, p.Option.WinMoneyModelID }].WinMoney != p.Option.WinMoney)
                        ups.Add(new { WinMoney = p.Option.WinMoney }, new
                        {
                            PlayTypeID = p.Option.PlayTypeID,
                            WinMoneyModelID = p.Option.WinMoneyModelID,
                            WinMoney = new ComparValue(Comparison.GreaterThan, p.Option.WinMoney),
                            @null = new ComparValue(Comparison.Sql, new SqlExpression("EXISTS (SELECT ID FROM Users AS t1 WHERE t1.ID = UserID AND t1.CommandID <> {1} AND t1.Commands LIKE {0})", string.Format("%{0}%", uid), uid))
                        });
                }
                base.BeginTransaction();
                base.Insert<PlayTypeOption_User>(ins.ToArray());
                base.Update<PlayTypeOption_User>(ups);
                rs = base.ExecuteTransaction();
            }
            return rs;
        }

        /// <summary>
        /// 设置用户奖金与返点 注（返点为百分比，不用除100）
        /// </summary>
        /// <param name="uid">要设置的用户ID,为NULL 表示设置站点的奖金</param>
        /// <param name="options">要设置的内容</param>
        public int SetUserOption(Guid? uid, IEnumerable<WinMoneyOption> options)
        {
            int rs = 0;
            var cus = base.Tables.PlayTypeOption.Select(p => new { p.PlayTypeID, p.WinMoneyModelID, p.WinMoney, p.BackMoneyRatio, p.BackMoneyToWinMoneyRatio, p.MaxBackMoneyToWinMoney }).ToArray();
            if (uid.HasValue)
                cus = base.Tables.PlayTypeOption_User.Where(p => p.UserID == uid).Select(p => new { p.PlayTypeID, p.WinMoneyModelID, p.WinMoney, p.BackMoneyRatio, BackMoneyToWinMoneyRatio = (decimal)0, MaxBackMoneyToWinMoney = (decimal)0 }).ToArray();
            var useSiteWin = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            var useSiteBack = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);

            var ins = new List<object>();
            var ups = new NameValue<object, object>();
            var upus = new NameValue<object, object>();
            base.BeginTransaction();

            foreach (var item in options)
            {
                var pl = CacheManage.PlayType[item.PlayTypeID];
                var lottery = ((LotteryType)pl.LotteryID).GetDefaultLottery();
                if (pl.LotteryID != (int)lottery)
                {
                    var tp = CacheManage.PlayType.Values.FirstOrDefault(pp => pp.PlayTypeListID == pl.PlayTypeListID && pp.LotteryID == (int)lottery);
                    if (tp != null)
                        item.PlayTypeID = tp.ID;
                }

                //返点单位换算
                var _backMoneyRatio = (decimal)item.BackMoneyRatio / 100;
                var _maxBackMoneyToWinMoney = (decimal)item.MaxBackMoneyToWinMoney / 100;
                
                //更新前数据
                var item1 = cus.FirstOrDefault(p => p.WinMoneyModelID == item.WinMoneyModelID && p.PlayTypeID == item.PlayTypeID);

                if (item1 == null)//新增
                {
                    if(uid.HasValue)
                        ins.Add(new { UserID = uid, item.PlayTypeID, item.WinMoneyModelID, item.WinMoney, BackMoneyRatio = _backMoneyRatio });
                    else
                        ins.Add(new { item.PlayTypeID, item.WinMoneyModelID, item.WinMoney, BackMoneyRatio = _backMoneyRatio, item.BackMoneyToWinMoneyRatio, item.MaxBackMoneyToWinMoney });
                }
                else//更新
                {
                    var up = new NameValue<string, object>();

                    //奖金设置
                    if ((double)item1.WinMoney != item.WinMoney && (!uid.HasValue || !useSiteWin))
                        up.Add("WinMoney", item.WinMoney);

                    //重置奖金
                    if (item.ResetWinMoney)
                    {
                        if (uid.HasValue)
                            upus.Add(new { item.WinMoney }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, @null = new ComparValue(Comparison.Sql, new SqlExpression("Exists (select ID from Users as t1 where t1.ID = UserID and t1.Commands like {0})", string.Format("%{0}%", uid), uid)) });
                        else
                            upus.Add(new { item.WinMoney }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID });
                    }
                    else if (!useSiteWin)
                    {
                        if ((double)item1.WinMoney > item.WinMoney && uid.HasValue)
                            upus.Add(new { item.WinMoney }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, WinMoney = new ComparValue(Comparison.GreaterThan, item.WinMoney), @null = new ComparValue(Comparison.Sql, new SqlExpression("Exists (select ID from Users as t1 where t1.ID = UserID and t1.Commands like {0})", string.Format("%{0}%", uid), uid)) });
                        else if ((double)item1.WinMoney > item.WinMoney)
                            upus.Add(new { item.WinMoney }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, WinMoney = new ComparValue(Comparison.GreaterThan, item.WinMoney) });
                    }

                    //返点设置
                    if (item1.BackMoneyRatio != _backMoneyRatio && (!uid.HasValue || !useSiteBack))
                        up.Add("BackMoneyRatio", _backMoneyRatio);

                    //重置返点
                    if (item.ResetBackMoneyRatio)
                    {
                        if (uid.HasValue)
                            upus.Add(new { BackMoneyRatio = _backMoneyRatio }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, @null = new ComparValue(Comparison.Sql, new SqlExpression("Exists (select ID from Users as t1 where t1.ID = UserID and t1.Commands like {0})", string.Format("%{0}%", uid), uid)) });
                        else
                            upus.Add(new { BackMoneyRatio = _backMoneyRatio }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID });
                    }
                    else if (!useSiteBack)
                    {
                        if (item1.BackMoneyRatio > _backMoneyRatio && uid.HasValue)
                            upus.Add(new { BackMoneyRatio = _backMoneyRatio }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, BackMoneyRatio = new ComparValue(Comparison.GreaterThan, _backMoneyRatio), @null = new ComparValue(Comparison.Sql, new SqlExpression("Exists (select ID from Users as t1 where t1.ID = UserID and t1.Commands like {0})", string.Format("%{0}%", uid), uid)) });
                        else if (item1.BackMoneyRatio > _backMoneyRatio)
                            upus.Add(new { BackMoneyRatio = _backMoneyRatio }, new { PlayTypeID = item.PlayTypeID, WinMoneyModelID = item.WinMoneyModelID, BackMoneyRatio = new ComparValue(Comparison.GreaterThan, _backMoneyRatio) });
                    }

                    //返点加奖设置
                    if(!uid.HasValue)
                    {
                        if((double)item1.BackMoneyToWinMoneyRatio != item.BackMoneyToWinMoneyRatio)
                            up.Add("BackMoneyToWinMoneyRatio", item.BackMoneyToWinMoneyRatio);
                        if(item1.MaxBackMoneyToWinMoney != _maxBackMoneyToWinMoney)
                            up.Add("MaxBackMoneyToWinMoney", _maxBackMoneyToWinMoney);
                    }

                    if (up.Count > 0)
                        ups.Add(up, uid.HasValue ? (object)new { item.PlayTypeID, item.WinMoneyModelID, UserID = uid } : (object)new { item.PlayTypeID, item.WinMoneyModelID });
                }
            }
            if (uid.HasValue)
            {
                base.Insert<PlayTypeOption_User>(ins.ToArray());
                base.Update<PlayTypeOption_User>(ups);
            }
            else
            {
                base.Insert<PlayTypeOption>(ins.ToArray());
                base.Update<PlayTypeOption>(ups);
            }
            base.Update<PlayTypeOption_User>(upus);
            rs = base.ExecuteTransaction();

            return rs;
        }
        /// <summary>
        /// 判断该用户是否存在
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool CheckUser(Guid uid)
        {
            bool playuser = false;
            using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
            {

                conn.Open();
                string sql = "select * from PlayTypeOption_User where userid=@uid";
                SqlCommand com = new SqlCommand(sql, conn);
                com.Parameters.AddWithValue("@uid", uid);
                SqlDataReader sdr = com.ExecuteReader();
                if (sdr.HasRows)
                {
                    playuser = true;
                }
            };
            return playuser;

        }
        /// <summary>
        /// 不能设置模式的返点的修改
        /// </summary>
        /// <param name="list"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int UpdateOptionUser(List<BackMoney> list, Guid uid)
        {
            int num = -1;
            foreach (BackMoney item in list)
            {
                using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
                {
                    conn.Open();
                    string sql = "update dbo.PlayTypeOption_User set BackMoneyRatio=@r where PlayTypeID in (select id  from dbo.PlayType where BackMoneyTypeID=@bd)and WinMoneyModelID=@wd and UserId=@name";
                    SqlCommand com = new SqlCommand(sql, conn);
                    com.Parameters.AddWithValue("@r", item.BackMoneyRatio / 100);
                    com.Parameters.AddWithValue("@bd", item.BackMoneyTypeId);
                    com.Parameters.AddWithValue("@wd", item.WinMoneyTypeID);
                    com.Parameters.AddWithValue("@name", uid);
                    num = com.ExecuteNonQuery();
                };
            }

            return num;
        }
        public int ResetWinMoney(int? winmodel, LotteryType? lottery, double? winmoney, double? ratio)
        {
            var where = new NameValue<string, object>();
            if (lottery.HasValue)
                where.Add("PlayTypeID", new ComparValue(Comparison.In, CacheManage.PlayType.Where(p => p.Value.LotteryID == (int)((LotteryType)lottery.Value).GetDefaultLottery()).Select(p => p.Value.ID)));
            if (winmodel.HasValue)
                where.Add("WinMoneyModelID", winmodel.Value);
            var update = new NameValue<string, object>();
            if (winmoney.HasValue)
                update.Add("WinMoney", new SqlExpression("CASE WHEN WinMoney + {0} > 0 THEN WinMoney + {0} ELSE 0 END", winmoney.Value));
            if (ratio.HasValue)
                update.Add("BackMoneyRatio", new SqlExpression("CASE WHEN BackMoneyRatio + {0} > 0 THEN BackMoneyRatio + {0} ELSE 0 END", ratio.Value / 100));
            int rs = 0;
            if (update.Count > 0)
            {
                base.BeginTransaction();
                base.Update<PlayTypeOption>(update, where);
                base.Update<PlayTypeOption_User>(update, where);
                rs = base.ExecuteTransaction();
            }
            return rs;
        }


        /// <summary>
        /// 获取用户奖金、返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">要设置的用户ID</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> GetUserOption_Set(Guid uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;

            var user = base.Select<Users, Users>(s => s.First(p => p.ID == uid));
            if (user == null)
                throw new AppException("用户不存在！");
            var self = this.GetWinMoneyOption(uid, lottery, winModel, ckUseSite, replace);
            var cmd = this.GetWinMoneyOption(user.CommandID, lottery, winModel, ckUseSite, replace);
            var site = this.GetWinMoneyOption(null, lottery, winModel, ckUseSite, replace);
            items = BuildSets(self, cmd, site);

            return items;
        }


        /// <summary>
        /// 获取用户奖金设置
        /// </summary>
        /// <param name="uid">用户的ID ，为空则获取站点的设置</param>
        /// <param name="ckUseSite">是否检查使用站点设置</param>
        /// <returns></returns>
        public WinMoneyOption[] GetOption(Guid? uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            int? type = lottery.HasValue ? ((int)((LotteryType)lottery.Value).GetDefaultLottery()) as int? : null;
            WinMoneyOption[] rs;
            var playuser = base.Select<PlayTypeOption_User, IQueryable<PlayTypeOption_User>>(s => s).Where(p => p.WinMoneyModel.State == 1);
            var playsite = base.Select(s => s).Where(p => p.WinMoneyModel.State == 1);
            var useSiteWin = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            var useSiteBack = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            List<BackMoneyRatioModel> list = new SiteManage().GetBackMoneyRatios();
            if (winModel.HasValue)
            {
                playsite = playsite.Where(p => p.WinMoneyModelID == winModel.Value);
                playuser = playuser.Where(p => p.WinMoneyModelID == winModel.Value);
            }

            if (!uid.HasValue)
            {
                rs = playsite.Select(p => p).GroupBy(p => new { p.WinMoneyModelID, p.PlayType.BackMoneyTypeID }, p => new WinMoneyOption
                {
                    LotteryID = p.PlayType.LotteryID,
                    PlayTypeListID = p.PlayType.PlayTypeListID,
                    BackMoneyTypeID = p.PlayType.BackMoneyTypeID,
                    PlayTypeID = p.PlayTypeID,
                    WinMoneyModelID = p.WinMoneyModelID,
                    WinMoney = (double)p.WinMoney,
                    BackMoneyRatio = (double)p.BackMoneyRatio,
                }).Select(p =>
                           p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                       ).ToArray();
            }
            else
            {
                var user = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.ID == uid));
                if (user == null)
                    throw new ValidateException("用户不存在");


                var commanders = user.Commands.Split("&".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => new Guid(p));
                playuser = playuser.Where(p => p.UserID == uid.Value && p.WinMoneyModel.State==1);
                playsite = playsite.Where(p => p.WinMoneyModel.State == 1);
                var UserType = base.Select<PlayTypeOption_User, PlayTypeOption_User>(p => p.FirstOrDefault(s => s.UserID == (Guid)uid));
                if (UserType == null)
                {
                    rs = playsite
                   .GroupJoin(playuser, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (site, users) => new { site, users = users })
                   .SelectMany(p => p.users.DefaultIfEmpty(), (p1, p2) => new { p1.site, user = p2 })
                   .GroupBy(p => new { p.site.PlayType.BackMoneyTypeID, p.site.WinMoneyModelID }, p => new WinMoneyOption
                   {
                       LotteryID = p.site.PlayType.LotteryID,
                       PlayTypeListID = p.site.PlayType.PlayTypeListID,
                       BackMoneyTypeID = p.site.PlayType.BackMoneyTypeID,
                       PlayTypeID = p.site.PlayTypeID,
                       WinMoneyModelID = p.site.WinMoneyModelID,
                       UserID = uid,
                       WinMoney = (double)(ckUseSite && useSiteWin ? p.site.WinMoney : p.user.WinMoney as decimal? ?? p.site.WinMoney),
                       BackMoneyRatio = (double)(p.site.BackMoneyRatio)
                   }).Select(p =>
                           p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                       ).ToArray();
                }
                else
                {
                    rs = playuser
                    .GroupJoin(playuser, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (site, users) => new { site, users = users })
                    .SelectMany(p => p.users.DefaultIfEmpty(), (p1, p2) => new { p1.site, user = p2 })
                    .GroupBy(p => new { p.site.PlayType.BackMoneyTypeID, p.site.WinMoneyModelID }, p => new WinMoneyOption
                    {
                        LotteryID = p.site.PlayType.LotteryID,
                        PlayTypeListID = p.site.PlayType.PlayTypeListID,
                        BackMoneyTypeID = p.site.PlayType.BackMoneyTypeID,
                        PlayTypeID = p.site.PlayTypeID,
                        WinMoneyModelID = p.site.WinMoneyModelID,
                        States = (int)p.site.State,
                        UserID = uid,
                        WinMoney = (double)(ckUseSite && useSiteWin ? p.site.WinMoney : p.user.WinMoney as decimal? ?? p.site.WinMoney),
                        BackMoneyRatio = (double)(p.site.BackMoneyRatio)
                    }).Select(p =>
                            p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                        ).ToArray();
                }

            }
            if (replace && type.HasValue && type != lottery)
            {
                rs.Each(p =>
                {
                    var tp = CacheManage.PlayType.Values.FirstOrDefault(pp => pp.PlayTypeListID == p.PlayTypeListID && pp.LotteryID == lottery);
                    if (tp != null)
                        p.PlayTypeID = tp.ID;
                });
            }
            int num = 0;
            foreach (var item in rs)
            {
                foreach (var back in list)
                {
                    if (item.WinMoneyModelID == back.WinModelID)
                    {
                        if (back.key == Option_Site_Key.Site_Lottery_MinBackMoneyRatio)
                        {

                            rs[num].MinBackMoneyRatio = Convert.ToDouble(back.Value);
                        }
                        else if (back.key == Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio)
                        {
                            rs[num].MaxBackMoneyRatio = Convert.ToDouble(back.Value);
                        }
                    }
                }
                num++;
            }

            return rs;
        }
        /// <summary>
        /// 前台添加时获取用户奖金设置
        /// </summary>
        /// <param name="uid">用户的ID ，为空则获取站点的设置</param>
        /// <param name="ckUseSite">是否检查使用站点设置</param>
        /// <returns></returns>
        public WinMoneyOption[] AddGetOption(Guid? uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {

            int? type = lottery.HasValue ? ((int)((LotteryType)lottery.Value).GetDefaultLottery()) as int? : null;
            WinMoneyOption[] rs;
            var playuser = base.Select<PlayTypeOption_User, IQueryable<PlayTypeOption_User>>(s => s).Where(p => p.WinMoneyModel.State == 1);
            var playsite = base.Select(s => s).Where(p=>p.WinMoneyModel.State==1);
            var useSiteWin = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            var useSiteBack = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            List<BackMoneyRatioModel> list = new SiteManage().GetBackMoneyRatios();


            if (winModel.HasValue)
            {
                playsite = playsite.Where(p => p.WinMoneyModelID == winModel.Value);
                playuser = playuser.Where(p => p.WinMoneyModelID == winModel.Value);
            }

            if (!uid.HasValue)
            {
                rs = playsite.Select(p => new WinMoneyOption
                {
                    LotteryID = p.PlayType.LotteryID,
                    PlayTypeListID = p.PlayType.PlayTypeListID,
                    BackMoneyTypeID = p.PlayType.BackMoneyTypeID,
                    PlayTypeID = p.PlayTypeID,
                    WinMoneyModelID = p.WinMoneyModelID,
                    WinMoney = (double)p.WinMoney,
                    BackMoneyRatio = (double)p.BackMoneyRatio,
                }).ToArray();
            }
            else
            {

                var user = base.Select<Users, Users>(s => s.First(p => p.ID == uid));
                if (user == null)
                    throw new AppException("用户不存在！");
                playuser = playuser.Where(p => p.UserID == uid.Value && p.WinMoneyModel.State==1);

                if (useSiteBack==true)
                {
                    playuser = playuser.Where(p => p.WinMoneyModel.State == 1);
                }
                var PlayUsertype = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.ID == uid));
                rs = playuser
                   .GroupJoin(playuser, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (site, users) => new { site, users = users })
                   .SelectMany(p => p.users.DefaultIfEmpty(), (p1, p2) => new { p1.site, user = p2 })
                   .GroupBy(p => new { p.site.PlayType.BackMoneyTypeID, p.site.WinMoneyModelID }, p => new WinMoneyOption
                   {
                       LotteryID = p.site.PlayType.LotteryID,
                       PlayTypeListID = p.site.PlayType.PlayTypeListID,
                       BackMoneyTypeID = p.site.PlayType.BackMoneyTypeID,
                       PlayTypeID = p.site.PlayTypeID,
                       WinMoneyModelID = p.site.WinMoneyModelID,
                       States = (int)p.site.State,
                       UserID = uid,
                       WinMoney = (double)(ckUseSite && useSiteWin ? p.site.WinMoney : p.user.WinMoney as decimal? ?? p.site.WinMoney),
                       BackMoneyRatio = (double)(p.site.BackMoneyRatio),
                   }).Select(p =>
                           p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                       ).ToArray();

            }
            if (replace && type.HasValue && type != lottery)
            {
                rs.Each(p =>
                {
                    var tp = CacheManage.PlayType.Values.FirstOrDefault(pp => pp.PlayTypeListID == p.PlayTypeListID && pp.LotteryID == lottery);
                    if (tp != null)
                        p.PlayTypeID = tp.ID;
                });
            }
            int num = 0;
            foreach (var item in rs)
            {
                foreach (var back in list)
                {
                    if (item.WinMoneyModelID == back.WinModelID)
                    {
                        if (back.key == Option_Site_Key.Site_Lottery_MinBackMoneyRatio)
                        {
                            rs[num].MinBackMoneyRatio = Convert.ToDouble(back.Value);
                        }
                        else if (back.key == Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio)
                        {
                            rs[num].MaxBackMoneyRatio = Convert.ToDouble(back.Value);
                        }
                    }
                }
                num++;
            }
            return rs;
        }

        private void GetBackMoneyRatios()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        ///后台 添加时获取用户奖金设置
        /// </summary>
        /// <param name="uid">用户的ID ，为空则获取站点的设置</param>
        /// <param name="ckUseSite">是否检查使用站点设置</param>
        /// <returns></returns>
        public WinMoneyOption[] LoginAddGetOption(Guid? uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {

            int? type = lottery.HasValue ? ((int)((LotteryType)lottery.Value).GetDefaultLottery()) as int? : null;
            WinMoneyOption[] rs;
            var playuser = base.Select<PlayTypeOption_User, IQueryable<PlayTypeOption_User>>(s => s).Where(p => p.WinMoneyModel.State == 1);
            var playsite = base.Select(s => s).Where(p=>p.WinMoneyModel.State==1);
            var useSiteWin = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            var useSiteBack = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);

            if (winModel.HasValue)
            {
                playsite = playsite.Where(p => p.WinMoneyModelID == winModel.Value);
                playuser = playuser.Where(p => p.WinMoneyModelID == winModel.Value);
            }

            if (!uid.HasValue)
            {
                rs = playsite.Select(p => new WinMoneyOption
                {
                    LotteryID = p.PlayType.LotteryID,
                    PlayTypeListID = p.PlayType.PlayTypeListID,
                    BackMoneyTypeID = p.PlayType.BackMoneyTypeID,
                    PlayTypeID = p.PlayTypeID,
                    WinMoneyModelID = p.WinMoneyModelID,
                    WinMoney = (double)p.WinMoney,
                    BackMoneyRatio = (double)p.BackMoneyRatio,
                }).ToArray();
            }
            else
            {
                var admin = base.Select<Admin, Admin>(s => s.First(p => p.ID == uid));
                if (admin == null)
                {
                    throw new AppException("用户不存在！");

                }
                if (useSiteBack)
                {
                    playsite = playsite.Where(p => p.WinMoneyModel.State == 1);
                }
                rs = playsite
                   .GroupJoin(playsite, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (site, users) => new { site, users = users })
                   .SelectMany(p => p.users.DefaultIfEmpty(), (p1, p2) => new { p1.site, user = p2 })
                   .GroupBy(p => new { p.site.PlayType.BackMoneyTypeID, p.site.WinMoneyModelID }, p => new WinMoneyOption
                   {
                       LotteryID = p.site.PlayType.LotteryID,
                       PlayTypeListID = p.site.PlayType.PlayTypeListID,
                       BackMoneyTypeID = p.site.PlayType.BackMoneyTypeID,
                       PlayTypeID = p.site.PlayTypeID,
                       WinMoneyModelID = p.site.WinMoneyModelID,
                       UserID = uid,
                       WinMoney = (double)(ckUseSite && useSiteWin ? p.site.WinMoney : p.user.WinMoney as decimal? ?? p.site.WinMoney),
                       BackMoneyRatio = (double)(ckUseSite && useSiteBack ? p.site.BackMoneyRatio : p.user.BackMoneyRatio as decimal? ?? p.site.BackMoneyRatio)
                   }).Select(p =>
                           p.OrderBy(pp => pp.WinMoney).OrderBy(pp => pp.BackMoneyRatio).FirstOrDefault()
                       ).ToArray();

            }
            if (replace && type.HasValue && type != lottery)
            {
                rs.Each(p =>
                {
                    var tp = CacheManage.PlayType.Values.FirstOrDefault(pp => pp.PlayTypeListID == p.PlayTypeListID && pp.LotteryID == lottery);
                    if (tp != null)
                        p.PlayTypeID = tp.ID;
                });
            }
            return rs;
        }
        /// <summary>
        ///后台添加时 获取用户返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">要设置的用户ID</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> GetOption_Set(Guid uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;
            var user = base.Select<Users, Users>(s => s.First(p => p.ID == uid));
            if (user == null)
                throw new AppException("用户不存在！");
            var self = this.AddGetOption(uid, lottery, winModel, ckUseSite, replace);
            var cmd = this.AddGetOption(user.CommandID, lottery, winModel, ckUseSite, replace);
            var site = this.AddGetOption(null, lottery, winModel, ckUseSite, replace);
            items = BuildSets(self, cmd, site);

            return items;
        }
        /// <summary>
        ///后台添加时 获取用户返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">要设置的用户ID</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> LoginGetOption_Set(Guid uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;
            var admin = base.Select<Admin, Admin>(s => s.First(p => p.ID == uid));
            if (admin == null)
            {
                throw new AppException("用户不存在！");
            }

            var self = this.LoginAddGetOption(uid, lottery, winModel, ckUseSite, replace);
            var cmd = this.LoginAddGetOption(uid, lottery, winModel, ckUseSite, replace);
            var site = this.LoginAddGetOption(null, lottery, winModel, ckUseSite, replace);
            items = BuildSets(self, cmd, site);

            return items;
        }
        /// <summary>
        ///前台获取用户返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">要设置的用户ID</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> AddGetOption_Set(Guid uid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;
            var user = base.Select<Users, Users>(s => s.First(p => p.ID == uid));
            if (user == null)
                throw new AppException("用户不存在！");
            var self = this.AddGetOption(uid, lottery, winModel, ckUseSite, replace);
            var cmd = this.AddGetOption(uid, lottery, winModel, ckUseSite, replace);
            var site = this.AddGetOption(null, lottery, winModel, ckUseSite, replace);
            items = BuildSets(self, cmd, site);

            return items;
        }
        /// <summary>
        /// 获取用户下级奖金、返点设置 注（返点为百分比，已乘以100）
        /// </summary>
        /// <param name="uid">当前用户的ID ,为 NULL时则为站点</param>
        /// <param name="lottery">彩种ID</param>
        /// <param name="winModel">奖金模式</param>
        /// <param name="playTypeID">指定的玩法</param>
        public IEnumerable<WinMoneyOptionSetItem> GetUserOption_SetWithChild(Guid? cmdid, int? lottery, int? winModel, bool ckUseSite, bool replace = true)
        {
            IEnumerable<WinMoneyOptionSetItem> items;
            if (cmdid.HasValue)
            {
                var self = this.GetWinMoneyOption(cmdid, lottery, winModel, ckUseSite, replace);
                var cmd = self;
                var site = this.GetWinMoneyOption(null, lottery, winModel, ckUseSite, replace);
                items = BuildSets(self, cmd, site);
            }
            else
            {
                var site = this.GetWinMoneyOption(null, lottery, winModel, ckUseSite, replace);
                items = BuildSets(null, site, site);
            }
            return items;
        }

        /// <summary>
        /// 生成奖金设置的内容
        /// </summary>
        /// <param name="self">要设置的用户，为空时表示生成站点的奖金设置 </param>
        /// <param name="cmd">上级的设置</param>
        /// <param name="site">站点的设置</param>
        /// <returns></returns>
        private static IEnumerable<WinMoneyOptionSetItem> BuildSets(WinMoneyOption[] self, WinMoneyOption[] cmd, WinMoneyOption[] site)
        {

            IEnumerable<WinMoneyOptionSetItem> items;

            if (self == null && cmd == null)
            {
                items = site.Select(p =>
                {
                    var tp = new WinMoneyOptionSetItem
                    {
                        PlayName = CacheManage.Playlist[(PlayType_E)p.PlayTypeListID].Name,
                        PlayNames = CacheManage.BackMoneyType[Convert.ToInt32(p.BackMoneyTypeID)].Name,
                        LotteryName = CacheManage.Lottery[(LotteryType)p.LotteryID].Name,
                        WinMoneyName = CacheManage.WinModel[p.WinMoneyModelID].Name,
                        BackMoneyName = CacheManage.BackMoneyType[Convert.ToInt32(p.BackMoneyTypeID)].Name,
                        PlaySort = CacheManage.PlayType[p.PlayTypeID].Sort,

                        States = CacheManage.PlayTypeOption[p.States].State == 0 ? true : false,
                        Option = p,
                    };

                    tp.MaxBackMoneyRatio *= 100;
                    tp.MinBackMoneyRatio *= 100;
                    tp.Option.BackMoneyRatio *= 100;

                    tp.Option.BackMoneyToWinMoneyRatio *= 100;

                    return tp;
                });
            }
            else
            {
                if (self == null)
                    self = cmd;

                // 最低保障金额比率,默认:0
                var MinWinMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinWinMoneyRatio].ToDouble(0) / 100;
                //最大反奖差比率,默认:1
                var MaxBackWinMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MaxBackWinMoneyMarginRatio].ToDouble(100) / 100;
                //最小返奖差比率，默认：0
                var MinBackWinMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackWinMoneyMarginRatio].ToDouble(0) / 100;
                // 最低保障返点比率,默认:0
                var MinBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackMoneyRatio].ToDouble(0) / 100;
                // 最大返点差,默认:1
                var MaxBackMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio].ToDouble(100) / 100;
                // 最小返点差,默认:0
                var MinBackMoneyMarginRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio].ToDouble(0) / 100;

                items = self.Join(cmd, p => new { p.PlayTypeID, p.WinMoneyModelID }, p => new { p.PlayTypeID, p.WinMoneyModelID }, (Self, Cmd) => new { Self, Cmd })
                     .Select(p =>
                     {
                         var tp = new WinMoneyOptionSetItem();
                         tp.PlayName = CacheManage.Playlist[(PlayType_E)p.Self.PlayTypeListID].Name;
                         tp.PlayNames = CacheManage.BackMoneyType[Convert.ToInt32(p.Self.BackMoneyTypeID)].Name;
                         tp.LotteryName = CacheManage.Lottery[(LotteryType)p.Self.LotteryID].Name;
                         tp.WinMoneyName = CacheManage.WinModel[p.Self.WinMoneyModelID].Name;
                         tp.BackMoneyName = CacheManage.BackMoneyType[Convert.ToInt32(p.Self.BackMoneyTypeID)].Name;
                         tp.PlaySort = CacheManage.PlayType[p.Self.PlayTypeID].Sort;
                         tp.Option = p.Self;
                         tp.CurrentBackMoneyRatio = p.Cmd.BackMoneyRatio;
                         tp.CurrentWimMoney = p.Cmd.WinMoney;

                         tp.MaxWinMoney = Math.Max(p.Cmd.WinMoney - (p.Cmd.WinMoney * MinBackWinMoneyMarginRatio), 0);

                         tp.States = p.Self.States == 0 ? true : false;
                         tp.MyState = p.Cmd.States == 0 ? true : false;
                         if (tp.MinWinMoney > tp.MaxWinMoney)
                             tp.MaxWinMoney = tp.MinWinMoney;
                         tp.MaxWinMoney = Math.Min(tp.MaxWinMoney, p.Cmd.WinMoney);
                         tp.MinWinMoney = Math.Min(tp.MinWinMoney, p.Cmd.WinMoney);
                         tp.Option.BackMoneyRatio = Math.Round(tp.Option.BackMoneyRatio * 100, 9);
                         tp.CurrentBackMoneyRatio = Math.Round(tp.CurrentBackMoneyRatio * 100, 9);

                         tp.Option.MaxBackMoneyToWinMoney = Math.Round(tp.Option.MaxBackMoneyToWinMoney * 100, 9);
                         return tp;
                     });
                if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false)==false)
                {
                    items = items.Where(p => p.MyState == true);
                }
               
                int cout = 0;
                var rels = items.ToArray();
                List<BackMoneyRatioModel> list = new SiteManage().GetBackMoneyRatios();
                foreach (var item in rels)
                {
                    foreach (var back in list)
                    {
                        if (item.Option.WinMoneyModelID == back.WinModelID)
                        {
                            if (back.key == Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio)
                            {

                                if (rels[cout].Option.MinBackMoneyRatio <= (item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value)))
                                {
                                    rels[cout].Option.MinBackMoneyRatio = item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value);
                                }
                            }
                            else if (back.key == Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio)
                            {
                                if (rels[cout].Option.MaxBackMoneyRatio >= (item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value)))
                                {
                                    rels[cout].Option.MaxBackMoneyRatio = item.CurrentBackMoneyRatio - Convert.ToDouble(back.Value);
                                }

                            }
                        }
                    }
                    cout++;
                }
                items = rels;
            }
            return items.ToArray();
        }
        /// <summary>
        /// 删除用户玩法设置表中记录，(在当前用户的直属下级中有人的指定玩法指定模式的设置比当前用户的高则删除此下级和下级和下级的指定玩法指定模式的记录)
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="paramList"></param>
        /// <returns></returns>
        private int DeleteUserOption(Guid uid, bool beginTran, params Delete_Where[] paramList)
        {
            var childs = base.Select<Users, IEnumerable<GetChidsResult>>(s => s.Where(p => p.CommandID == uid).Select(p => new GetChidsResult { ID = p.ID, CommandID = p.CommandID }));
            var deleteIDs = new List<Key<long, decimal?, decimal?>>();
            if (beginTran)
                base.BeginTransaction();
            foreach (var item in paramList)
            {
                var childIds = base.Select<PlayTypeOption_User, IEnumerable<Guid>>(s => s.Where(p => p.PlayTypeID == item.PlayTypeID &&
                    p.WinMoneyModelID == item.WinMoneyModelID && childs.Select(p1 => p1.ID).Contains(p.UserID))
                    .Where(p => p.WinMoney > item.WinMoney && item.WinMoney != null || p.BackMoneyRatio > item.BackMoneyRatio && item.BackMoneyRatio != null)
                    .Select(p => p.UserID)).ToArray();
                foreach (var childID in childIds)
                {
                    var childList = base.GetUserChild_ContainMe(childID);
                    var optionIds = base.Select<PlayTypeOption_User, IEnumerable<Key<long, decimal?, decimal?>>>(s => s.Where(p => childList.Select(p1 => p1.ID).Contains(p.UserID) && p.WinMoneyModelID == item.WinMoneyModelID && p.PlayTypeID == item.PlayTypeID).Select(p => new Key<long, decimal?, decimal?>(p.ID, item.WinMoney, item.BackMoneyRatio)));
                    deleteIDs.AddRange(optionIds);
                }
            }

            Func<Key<long, decimal?, decimal?>, object> fun = (p) =>
            {
                var temp = new NameValue<string, object>();
                if (p.Propertie2.HasValue)
                    temp.Add("WinMoney", p.Propertie2.Value);
                if (p.Propertie3.HasValue)
                    temp.Add("BackMoneyRatio", p.Propertie3.Value);
                return temp as object;
            };

            base.Update<PlayTypeOption_User>(deleteIDs.ToNameValue(fun, p => new { ID = p.Propertie1 } as object));
            if (beginTran)
                return base.ExecuteTransaction(deleteIDs.Count);
            return -1;
        }
        /// <summary>
        ///可以设置模式的返点的修改
        /// </summary>    
        /// <param name="list"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public int UpdateOption(List<BackMoney> list, Guid uid)
        {
            int num = -1;
            foreach (BackMoney item in list)
            {
                using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
                {
                    conn.Open();
                    string sql = "update dbo.PlayTypeOption_User set  BackMoneyRatio=@r,State=@state where PlayTypeID in (select id  from dbo.PlayType where BackMoneyTypeID=@bd)and WinMoneyModelID=@wd and UserId=@uid and WinMoneyModelID in (select id from WinMoneyModel where state=1)";
                    SqlCommand com = new SqlCommand(sql, conn);
                    com.Parameters.AddWithValue("@r", item.BackMoneyRatio / 100);
                    com.Parameters.AddWithValue("@bd", item.BackMoneyTypeId);
                    com.Parameters.AddWithValue("@wd", item.WinMoneyTypeID);
                    com.Parameters.AddWithValue("@uid", uid);
                    if (item.States == true)
                    {
                        com.Parameters.AddWithValue("@state", 0);
                    }
                    else
                    {
                        com.Parameters.AddWithValue("@state", 1);
                    }
                    num = com.ExecuteNonQuery();
                };

            }


            return num;
        }
        /// <summary>
        ///模式修改
        /// </summary>
        /// <param name="list"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int Updatewin(List<BackMoney> list, string loginName)
        {
            int num = -1;
            foreach (BackMoney item in list)
            {
                using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
                {
                    conn.Open();
                    string sql = "update dbo.PlayTypeOption_User set state=@state where PlayTypeID in (select id  from dbo.PlayType where BackMoneyTypeID=@bd)and WinMoneyModelID=@wd and UserId=(select id from Users where LoginName=@name) and WinMoneyModelID in (select id from WinMoneyModel where state=1)";
                    SqlCommand com = new SqlCommand(sql, conn);
                    com.Parameters.AddWithValue("@bd", item.BackMoneyTypeId);
                    com.Parameters.AddWithValue("@wd", item.WinMoneyTypeID);
                    com.Parameters.AddWithValue("@name", loginName);
                    if (item.States == true)
                    {
                        com.Parameters.AddWithValue("@state", 0);
                    }
                    else
                    {
                        com.Parameters.AddWithValue("@state", 1);
                    }
                    num = com.ExecuteNonQuery();
                };

            }
            return num;
        }
        /// <summary>
        ///可以设置模式登陆时返点的修改
        /// </summary>
        /// <param name="list"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int LoginUpdateOption(List<BackMoney> list, string loginName)
        {
            int num = -1;
            foreach (BackMoney item in list)
            {
                using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
                {
                    conn.Open();
                    string sql = "update dbo.PlayTypeOption_User set BackMoneyRatio=@r , state=@state where PlayTypeID in (select id  from dbo.PlayType where BackMoneyTypeID=@bd)and WinMoneyModelID=@wd and UserId=(select id from Users where LoginName=@name) and WinMoneyModelID in (select id from WinMoneyModel where state=1)";
                    SqlCommand com = new SqlCommand(sql, conn);
                    com.Parameters.AddWithValue("@r", item.BackMoneyRatio / 100);
                    com.Parameters.AddWithValue("@bd", item.BackMoneyTypeId);
                    com.Parameters.AddWithValue("@wd", item.WinMoneyTypeID);
                    com.Parameters.AddWithValue("@name", loginName);
                    if (item.States == true)
                    {
                        com.Parameters.AddWithValue("@state", 0);
                    }
                    else
                    {
                        com.Parameters.AddWithValue("@state", 1);
                    }
                    num = com.ExecuteNonQuery();
                };

            }
            return num;
        }

        /// <summary>
        ///不可以设置磨模式的登陆时返点的修改
        /// </summary>
        /// <param name="list"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int LoginUpdateUserOption(List<BackMoney> list, string loginName)
        {
            int num = -1;
            foreach (BackMoney item in list)
            {
                using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
                {
                    conn.Open();
                    string sql = "update dbo.PlayTypeOption_User set BackMoneyRatio=@r , state=@state where PlayTypeID in (select id  from dbo.PlayType where BackMoneyTypeID=@bd)and WinMoneyModelID=@wd and UserId=(select id from Users where LoginName=@name)";
                    SqlCommand com = new SqlCommand(sql, conn);
                    com.Parameters.AddWithValue("@r", item.BackMoneyRatio / 100);
                    com.Parameters.AddWithValue("@bd", item.BackMoneyTypeId);
                    com.Parameters.AddWithValue("@wd", item.WinMoneyTypeID);
                    com.Parameters.AddWithValue("@name", loginName);
                    if (item.States == true)
                    {
                        com.Parameters.AddWithValue("@state", 0);
                    }
                    else
                    {
                        com.Parameters.AddWithValue("@state", 1);
                    }
                    num = com.ExecuteNonQuery();
                };

            }
            return num;
        }
        /// <summary>
        /// 枚举代理是否可以设置下级的模式
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool SelectFromOption_SetById()
        {
            bool b = false;
            using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
            {
                conn.Open();
                string sql = "select [Value] from  dbo.Option_Site where [Key]=@key";
                SqlCommand com = new SqlCommand(sql, conn);
                com.Parameters.AddWithValue("@key", "Site_Cache_WinMoneyTypeID");

                b = Convert.ToBoolean(com.ExecuteScalar());


            }
            return b;
        }
        public static List<Code.Models.WinMoneyModel> SelectIdFromPlayTypeOption(Guid id)
        {
            List<Code.Models.WinMoneyModel> ls = null;
            using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
            {
                conn.Open();
                string sql = "";
                if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false))
                {
                     sql = "select * from  dbo.WinMoneyModel where state=1";
                }
                else
                {
                    sql = "select * from  dbo.WinMoneyModel where id in (select WinMoneyModelID from dbo.PlayTypeOption_User group by WinMoneyModelID,Userid,state having Userid=@UID  and state=0) and state=1";
                }
              
                SqlCommand com = new SqlCommand(sql, conn);
                com.Parameters.AddWithValue("@UID", id);
                SqlDataReader sdr = com.ExecuteReader();
                if (sdr.HasRows)
                {
                    ls = new List<Code.Models.WinMoneyModel>();
                }
                while (sdr.Read())
                {
                    Code.Models.WinMoneyModel wm = new Code.Models.WinMoneyModel();
                    wm.ID = Convert.ToInt32(sdr["id"]);
                    wm.Name = sdr["Name"].ToString();
                    ls.Add(wm);
                }
            }
            return ls;
        }
        public int InsertUpRank(string loginName)
        {
            var user = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.LoginName == loginName));
            int res = 0;
            Rank Rank = base.Select<Rank, Rank>(s => s.OrderBy(j => j.Exper).FirstOrDefault(p => p.Id != null));
            using (SqlConnection conn = new SqlConnection(DBHelper.Connection.ConnectionString))
            {
                conn.Open();
                string sql = "insert into dbo.UpRank(ThisExpert,UsersId,RankId) values(@thisExpert,@uid,@rank)";
                SqlCommand com = new SqlCommand(sql, conn);
                com.Parameters.AddWithValue("@thisExpert", 0);
                com.Parameters.AddWithValue("@uid", user.ID);
                com.Parameters.AddWithValue("@rank", Rank.Id);
                res = com.ExecuteNonQuery();

            }
            return res;
        }
        public Users Name(Guid uid) 
        {
            var users = base.Select<Users, Users>(s => s.FirstOrDefault(p => p.ID == uid));
            return users;
        }
        public class Delete_Where
        {
            public int PlayTypeID { get; set; }
            public int WinMoneyModelID { get; set; }
            public decimal? WinMoney { get; set; }
            public decimal? BackMoneyRatio { get; set; }
        }
        [Serializable]
        public class WinMoneyOption
        {

            public int PlayTypeID { get; set; }
            public int PlayTypeListID { get; set; }
            public int? BackMoneyTypeID { get; set; }
            public int LotteryID { get; set; }
            public int WinMoneyModelID { get; set; }
            public int States { get; set; }
            public Guid? UserID { get; set; }
            public double WinMoney { get; set; }
            public bool ResetWinMoney { get; set; }
            public double BackMoneyRatio { get; set; }
            public bool ResetBackMoneyRatio { get; set; }
            public bool WinMoneyState { get; set; }
            public double MaxBackMoneyRatio { get; set; }
            public double MinBackMoneyRatio { get; set; }


            public double BackMoneyToWinMoneyRatio { get; set; }
            public double MaxBackMoneyToWinMoney { get; set; }
        }
        [Serializable]
        public class WinMoneyOptionSetItem
        {
            public bool States { get; set; }
            public bool MyState { get; set; }
            public WinMoneyOption Option { get; set; }
            public double CurrentWimMoney { get; set; }
            public double CurrentBackMoneyRatio { get; set; }
            public double MaxWinMoney { get; set; }
            public double MinWinMoney { get; set; }
            public string WinMoneyName { get; set; }
            public string BackMoneyName { get; set; }
            public string LotteryName { get; set; }
            public string PlayName { get; set; }
            public string PlayNames { get; set; }
            public int? PlaySort { get; set; }
            public double MaxBackMoneyRatio { get; set; }
            public double MinBackMoneyRatio { get; set; }
        }
        [Serializable]
        public class BackMoney
        {
            public int BackMoneyTypeId { get; set; }
            public int WinMoneyTypeID { get; set; }
            public double BackMoneyRatio { get; set; }
            public bool States { get; set; }
        }

    }
}
